package Filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class experiment_5_1_Filter implements Filter {

    private FilterConfig filterConfig;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        this.filterConfig = filterConfig;
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        ServletContext context = this.filterConfig.getServletContext();
        long time = System.currentTimeMillis();
        String addr = servletRequest.getRemoteAddr();
        String name = servletRequest.getServerName();
        HttpServletRequest httpServletRequest = (HttpServletRequest)servletRequest;
        HttpServletResponse httpServletResponse = (HttpServletResponse)servletResponse;
        String uri = httpServletRequest.getRequestURI();
        System.out.println("开始写入");
        context.log("访问时间" + time + "远程地址" + addr + "远程主机名" + name + "资源URI" + uri);
        System.out.println("写入完成");
        HttpSession httpSession = httpServletRequest.getSession();
        if (httpSession.getAttribute("un") == "123")
            filterChain.doFilter(servletRequest,servletResponse);
        else
            httpServletResponse.sendRedirect("register.jsp");
    }

    @Override
    public void destroy() {
        this.filterConfig = null;
    }
}
